﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Vra.DataAccess.Entities;
using Vra.DataAccess.Misc;

namespace Vra.DataAccess
{
	public class NationDao : BaseDao, INationDao
	{
		/// <summary>
		/// Делаем своего рода кеш с национальностями
		/// </summary>
		private static readonly IDictionary<int, Nation> Nations;

		static NationDao()
		{
			Nations = new Dictionary<int, Nation>();
		}

		private IList<Nation> LoadInternal()
		{
			IList<Nation> nations = new List<Nation>();
			using (var conn = GetConnection())
			{
				conn.Open();
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = QueryManager.GetSelectQuery<Nation>(); //"SELECT NatID, Value FROM Nation";
					cmd.CommandType = CommandType.Text;
					using (var reader = cmd.ExecuteReader())
					{
						while (reader.Read())
						{
							nations.Add(LoadNation(reader));
						}
					}
				}
			}
			return nations;
		}

		public IList<Nation> Load()
		{
			//_nations = new Dictionary<int, Nation>();
			Nations.Clear();
			var nations = LoadInternal();
			foreach (var nation in nations)
			{
				Nations.Add(nation.Id, nation);
			}
			//return Nations.Values.ToList();
			return nations;
		}

		public Nation Get(int? id)
		{
			if (id == null)
				return null;
			int nid = id.Value;
			if (Nations.Count == 0)
				Load();
			return Nations.ContainsKey(nid) ? Nations[nid] : null;

		}

		public void Reset()
		{
			if (Nations == null)
				return;
			Nations.Clear();
		}

		private static Nation LoadNation(SqlDataReader reader)
		{
			return MiscUtils.Get<Nation>(reader);
			/*Nation nation = new Nation();
			nation.Id = reader.GetInt32(reader.GetOrdinal("NatID"));
			nation.Name = reader.GetString(reader.GetOrdinal("Value"));
			return nation;*/
		}

		public void Add(Nation Nation)
		{
			using (var conn = GetConnection())
			{
				conn.Open();
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = "INSERT INTO Nation (Value) VALUES (@Nation)";
					cmd.Parameters.AddWithValue("@Nation", Nation.Name);
					cmd.ExecuteNonQuery();
				}
			}
		}

		public void Delete(int id)
		{

			using (var conn = GetConnection())
			{
				conn.Open();
				using (var cmd = conn.CreateCommand())
				{
					cmd.CommandText = QueryManager.GetDelQuery<Nation>("@ID"); //"DELETE FROM Nation WHERE NatID = @ID";
					cmd.Parameters.AddWithValue("@ID", id);
					cmd.ExecuteNonQuery();
				}
			}
		}
	}
}